using Microsoft.AspNetCore.Mvc;
using WEB.API.Dto;
using WEB.API.Model;
namespace WEB.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]

    public class BlogController(WebDbContext db) : ControllerBase
    {
        //注入数据库上下文
        private readonly WebDbContext db = db;

        [HttpGet]
        public IActionResult Get()
        {
            //从数据库获取所有博客列表
            var list = db.Blogs.ToList();
            //返回成功响应
            return Ok(new { Code = 1000, Data = list, Msg = "查询博客列表成功" });
        }

        //通过关键字查询
        [HttpGet("search")]
        public IActionResult Search([FromQuery] BlogSearchDto dto)
        {
            //根据关键字查询博客
            var blog = db.Blogs
            .Where(b => b.Titel.Contains(dto.Keyword) || b.Content.Contains(dto.Keyword))
            .ToList();
            return Ok(new { Code = 1000, Data = blog, Msg = "查询成功" });
        }

        //新增博客
        [HttpPost]
        public IActionResult Post(BlogAddDto dto)
        {
            //创建新的博客对象
            var blog = new Blog
            {
                Titel = dto.Titel,
                Author = dto.Author,
                Content = dto.Content
            };

            //讲新博客添加到数据库
            db.Add(blog);
            //保存数据
            db.SaveChanges();
            //返回响应成功
            return Ok(new { Code = 1000, Data = new BlogResultDto(blog.Titel, blog.Author, blog.Content), Msg = "新增博客成功" });
        }

        //修改博客
        [HttpPut("{id}")]

        public IActionResult Put(int id, BlogUpdataDto dto)
        {
            //查找数据库查找数据
            var blog = db.Blogs.Find(id);
            //如果没有返回响应,就响应notFound
            if (blog == null) return NotFound();
            //更新博客信息
            blog.Titel = dto.Titel;
            blog.Author = dto.Author;
            blog.Content = dto.Content;
            //保存数据
            db.SaveChanges();
            //返回成功响应
            return Ok(new { Code = 1000, Msg = "修改成功" });

        }

        //删除博客
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            //查找数据库数据
            var blog = db.Blogs.Find(id);
            //如果没有对应数据，返回NotFound响应
            if (blog == null) return NotFound();
            //删除对应的博客数据
            db.Blogs.Remove(blog);
            //保存删除后的数据
            db.SaveChanges();
            //返回成功响应
            return Ok(new { Code = 1000, Msg = "删除博客成功" });

        }

    }

}